/*
 * Updater.java
 *
 * Created on August 1, 2007, 8:11 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package com.afaker.rss;

import com.afaker.rss.feed.biz.FeedFetcher;
import com.afaker.rss.feed.biz.FeedUpdatedListener;
import com.afaker.rss.feed.biz.ROMEFeedFetcher;
import com.afaker.rss.gui.Window;
import com.sun.syndication.fetcher.FetcherException;
import com.sun.syndication.io.FeedException;
import java.io.IOException;
import java.util.Iterator;
import java.util.Observable;
import java.util.Set;
import com.afaker.rss.feed.*;

/**
 *
 * @author bruce
 */
public class Updater extends Observable implements Runnable {
    private Window window;
    private FeedUpdatedListener listener;
    private FeedSet feeds;
    private EntrySet entries;
    private ChannelList list;
    
    
    /** Creates a new instance of Updater */
    public Updater(ChannelList list) {
        this.list = list;
        updateFeedSet();
    }
    
    private void updateFeedSet() {
        int REFRESH_PERIOD=1000;
        feeds = new FeedSet();
        Set feedURIs=list.getList();
        Iterator it=feedURIs.iterator();
        FeedFetcher feedFetcher = null;
        int nameCounter = 1;
        
        while (it.hasNext()) {
            try {
                feedFetcher = new ROMEFeedFetcher((String) it.next());
            } catch (IOException ex) {
                ex.printStackTrace();
            } catch (FeedException ex) {
                ex.printStackTrace();
            } catch (FetcherException ex) {
                ex.printStackTrace();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            if(feedFetcher == null)
                return ;
            feedFetcher.setRefreshPeriod(REFRESH_PERIOD);
            feeds.addFeed(feedFetcher);
        }
    }
    
    public FeedSet getFeedSet() {
        return feeds;
    }
    
    public void addFeedUpdatedListener(FeedUpdatedListener listener) {
        this.listener = listener;
    }
    
    public EntrySet getNewFeedEntry() {
        return entries;
    }
    
    public void run() {
        /**Wait for a while so that the main window can be shown quickly.*/
        try {
            Thread.sleep(10000);
        } catch (InterruptedException ex) {
            ex.printStackTrace();
        }
        while (true) {
            feeds.refreshAll();
            entries = feeds.getNewEntry();
            if(listener!=null)
                listener.actionPerformed();
        }
    }
}
